<template>
	<view class="event-detail-container">
		<!-- 赛事封面图 -->
		<image class="event-cover" :src="'http://localhost:8080' + event.imageUrl">
		</image>

		<!-- 赛事基本信息，用卡片样式包裹 -->
		<view class="event-info-card">
			<view class="event-info">
				<text class="section-title">
					赛事信息
				</text>
				<view class="info-item">
					<text class="info-label">赛事编号:</text>
					<text class="info-value">{{ event.id }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">赛事名称:</text>
					<text class="info-value">{{ event.name }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">报名费用:</text>
					<text class="info-value">￥{{ formatPrice(event.eventCost) }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">赛事类型:</text>
					<text class="info-value">
						<span v-if="event.isTeamBased === 1" style="margin-left: 5px;">
							个人
						</span>
						<span v-else-if="event.isTeamBased === 2" style="margin-left: 5px;">
							团体
						</span>
						<span v-else>
							未知类型
						</span>
					</text>
				</view>
				<view class="info-item">
					<text class="info-label">赛事开始时间:</text>
					<text class="info-value">{{ event.startTime }}</text>
				</view>
			</view>
		</view>

		<!-- 赛事介绍 -->
		<view class="event-introduction">
			<text class="section-title">
				赛事介绍
			</text>
			<text class="event-description">
				{{ event.description }}
			</text>
		</view>

		<!-- 举办地 -->
		<view class="event-registration">
			<text class="section-title">
				举办信息
			</text>
			<view class="info-item">
				<text class="info-label">主办方:</text>
				<text class="info-value">{{ event.createdBy }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">举办场地:</text>
				<text class="info-value">{{ event.address }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">赛事奖励:</text>
				<text class="info-value">{{ event.reward }}</text>
			</view>
			<!-- 假设这里有商家编码信息 -->
			<view class="info-item">
				<text class="info-label">商家编码:</text>
				<text class="info-value">{{ event.merchantId }}</text>
			</view>
		</view>

		<!-- 报名信息 -->
		<view class="event-registration">
			<text class="section-title">
				报名信息
			</text>
			<view class="info-item">
				<text class="info-label">报名时间:</text>
				<text class="info-value">{{ event.registrationStartTime }} - {{ event.registrationEndTime }}</text>
			</view>
			<!-- <view class="info-item">
                <text class="info-label">报名方式:</text>
                <text class="info-value">{{ event.registrationMethod }}</text>
            </view> -->
			<!-- 当 registrationStatus 为 3 或 null 时显示“立即报名”，否则显示“已报名” -->
			<!-- 如果报名已结束，显示“报名已结束”，并禁用 -->
			<button 
			  v-if="isRegistrationClosed"
			  class="register-button" 
			  :disabled="true">
			  报名已结束
			</button>
			
			<!-- 如果报名未结束，且 registrationStatus 为 3 或 null 时显示“立即报名”，否则显示“已报名” -->
			<button 
			  v-else-if="event.registrationStatus === 3 || event.registrationStatus === null"
			  class="register-button" 
			  :disabled="isRegistrationClosed" 
			  @click="openModal">
			  立即报名
			</button>
			
			<!-- 如果报名已完成，显示已报名，禁用按钮 -->
			<button 
			  v-else
			  class="register-button" 
			  :disabled="true">
			  已报名
			</button>

		</view>

		<!-- 报名对话框 -->
		<view :class="{ 'modal': true, 'show-modal': isModalVisible }">
			<view class="modal-content">
				<!-- <view class="close" @click="closeModal">&times;</view> -->
				<form @submit.prevent="submitForm">
					<div class="form-row">
						<label for="name">客户姓名：</label>
						<input type="text" id="name" v-model="formData.name" required placeholder="请输入客户姓名"
							@focus="clearError('name')" @blur="validateField('name')" disabled>
						<!-- <span v-if="errors.name" class="error-message">{{ errors.name }}</span> -->
					</div>

					<div class="form-row">
						<label for="contact">联系方式：</label>
						<input type="text" id="contact" v-model="formData.contact" required placeholder="请输入联系方式"
							@focus="clearError('contact')" @blur="validateField('contact')">
						<span v-if="errors.contact" class="error-message">{{ errors.contact }}</span>
					</div>

					<div class="form-row">
						<label for="merchantId">商家编码：</label>
						<input type="text" id="merchantId" v-model="formData.merchantId" required placeholder="请输入商家ID"
							@focus="clearError('merchantId')" @blur="validateField('merchantId')" disabled>
						<span v-if="errors.merchantId" class="error-message">{{ errors.merchantId }}</span>
					</div>

					<div class="form-row">
						<label for="eventId">赛事编码：</label>
						<input type="text" id="eventId" v-model="formData.eventId" :value="event.id" disabled>
					</div>

					<div class="form-row">
						<label for="registrationDate">报名日期：</label>
						<input type="date" id="registrationDate" v-model="formData.registrationDate" required
							@focus="clearError('registrationDate')" @blur="validateField('registrationDate')" disabled>
						<span v-if="errors.registrationDate" class="error-message">{{ errors.registrationDate }}</span>
					</div>

					<div class="form-row">
						<label for="eventTime">活动时间：</label>
						<input type="text" id="eventTime" v-model="formData.eventTime" :value="event.startTime"
							disabled>
					</div>

					<div class="form-row">
						<label for="participantCount">报名人数：</label>
						<input type="number" id="participantCount" v-model="formData.participantCount" required min="1"
							placeholder="请输入报名人数" @focus="clearError('participantCount')"
							@blur="validateField('participantCount')">
						<span v-if="errors.participantCount" class="error-message">{{ errors.participantCount }}</span>
					</div>

					<div class="form-row">
						<label for="participationMethod">参与方式：</label>
						<input type="text" id="participationMethod" v-model="getParticipationMethodText"
							:readonly="true" @focus="clearError('participationMethod')"
							@blur="validateField('participationMethod')" disabled>
						<span v-if="errors.participationMethod" class="error-message"
							
					</div>

					<div class="button-group">
						<button type="submit" @click="submitForm">提交</button>
						<button type="button" @click="cancelForm">取消</button>
					</div>
				</form>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getEventById,
		signUp
	} from '@/api/match/event.js';

	export default {
		data() {
			return {
				event: {},
				isRegistrationClosed: false,
				isModalVisible: false,
				formData: {
					name: '',
					contact: '',
					merchantId: '',
					eventId: '',
					registrationDate: '',
					eventTime: '',
					participantCount: '',
					participationMethod: ''
				},
				errors: {}
			};
		},
		onLoad(option) {
			const eventId = option.id;
			console.log(eventId);
			this.fetchEventDetail(eventId);
		},
		computed: {
			getParticipationMethodText() {
				if (this.formData.participationMethod === '1') {
					return '个人';
				} else if (this.formData.participationMethod === '2') {
					return '团队';
				}
				return '未选择';
			}
		},
		methods: {
			async fetchEventDetail(eventId) {
				try {
					const response = await getEventById(eventId);
					this.event = response.data;

					// 判断报名是否已结束
					const now = new Date();
					const endTime = new Date(this.event.registrationEndTime);
					this.isRegistrationClosed = now > endTime;
				} catch (error) {
					console.error('获取赛事详情失败', error);
				}
			},
			formatPrice(price) {
				if (typeof price !== 'number' || isNaN(price)) {
					return '0.00';
				}
				return price.toFixed(2);
			},

			openModal() {
				console.log('openModal 方法被调用');
				this.isModalVisible = true;
				this.errors = {};
				// 填充商家编码、赛事编码和活动时间到表单数据
				this.formData.merchantId = this.event.merchantId;
				this.formData.eventId = this.event.id;
				this.formData.eventTime = this.event.startTime;
				this.formData.participationMethod = this.event.isTeamBased;
				this.formData.name = this.$store.state.user.nickname

				// 获取当前日期并格式化为 YYYY-MM-DD 格式
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				this.formData.registrationDate = `${year}-${month}-${day}`;
                console.log('赛事信息',this.event);
				if (this.event.isTeamBased === 1) {
					this.formData.participationMethod = '1';
				} else if (this.event.isTeamBased === 2) {
					this.formData.participationMethod = '2';
				}

				// 自动聚焦到第一个输入框
				this.$nextTick(() => {
					const firstInput = this.$el.querySelector('input');
					if (firstInput) {
						firstInput.focus();
					}
				});
			},
			closeModal() {
				console.log('closeModal 方法被调用');
				this.isModalVisible = false;
				this.errors = {};
			},
			validateField(field) {
				switch (field) {
					case 'name':
						if (!this.formData.name) {
							this.errors.name = '客户姓名不能为空';
						} else {
							delete this.errors.name;
						}
						break;
					case 'contact':
						if (!this.formData.contact) {
							this.errors.contact = '联系方式不能为空';
						} else {
							delete this.errors.contact;
						}
						break;
					case 'merchantId':
						if (!this.formData.merchantId) {
							this.errors.merchantId = '商家ID不能为空';
						} else {
							delete this.errors.merchantId;
						}
						break;
					case 'registrationDate':
						if (!this.formData.registrationDate) {
							this.errors.registrationDate = '报名日期不能为空';
						} else {
							delete this.errors.registrationDate;
						}
						break;
					case 'participantCount':
						if (!this.formData.participantCount || this.formData.participantCount < 1) {
							this.errors.participantCount = '报名人数不能小于1';
						} else {
							delete this.errors.participantCount;
						}
						break;
					case 'participationMethod':
						if (!this.formData.participationMethod) {
							this.errors.participationMethod = '请选择参与方式';
						} else {
							delete this.errors.participationMethod;
						}
						break;
				}
			},
			clearError(field) {
				delete this.errors[field];
			},
			submitForm() {
				// 构建提交的表单数据对象
				const data = {
					customerName: this.formData.name, // 客户名字
					contactInfo: this.formData.contact, // 联系方式
					merchantId: this.formData.merchantId, // 商户ID
					activityId: this.formData.eventId, // 活动ID
					registrationDate: this.formData.registrationDate, // 注册日期
					eventTime: this.formData.eventTime, // 活动时间
					participantCount: this.formData.participantCount, // 参与人数
					participationMode: this.formData.participationMethod, // 参与方式
					paymentStatus: 0, // 支付状态，默认为0（未支付）
					registrationStatus: 0 // 注册状态，默认为0（未注册）
				};

				// 打印构建的data对象，查看数据
				console.log('data的数据是', data);

				// 提交前再次验证所有字段
				Object.keys(this.formData).forEach(field => {
					// 排除'eventId' 和 'eventTime' 字段进行验证
					if (field !== 'eventId' && field !== 'eventTime') {
						this.validateField(field); // 调用validateField方法进行字段验证
					}
				});

				// 如果没有验证错误（errors对象为空），则继续提交数据
				if (Object.keys(this.errors).length === 0) {
					// 打印表单数据
					console.log('表单数据：', this.formData);
					signUp(data).then(res => {
							console.log(res);
							const RegistrationID = res.data
							console.log('报名表的id是', RegistrationID);
							// 使用深拷贝的方式复制formData，以防止直接修改源数据
							const tempFormData = JSON.parse(JSON.stringify(this.formData));

							// 关闭模态框
							this.closeModal();

							// 清空表单数据，重置输入框内容
							this.formData = {
								name: '',
								contact: '',
								merchantId: '',
								eventId: '',
								registrationDate: '',
								eventTime: '',
								participantCount: '',
								participationMethod: ''
							};

							// 使用临时的表单数据进行页面跳转，传递数据到下一个页面
							uni.navigateTo({
								url: `/pages/match/order?event=${encodeURIComponent(JSON.stringify(this.event))}&formData=${encodeURIComponent(JSON.stringify(tempFormData))}&registrationId=${encodeURIComponent(RegistrationID)}`
							});
						})
						.catch(res => {
							console.log(res);
						})

				} else {
					// 如果验证未通过，打印错误信息
					console.log('验证未通过，错误信息:', this.errors);
				}
			},

			cancelForm() {
				console.log('cancelForm 方法被调用')
				this.formData = {
					name: '',
					contact: '',
					merchantId: '',
					eventId: '',
					registrationDate: '',
					eventTime: '',
					participantCount: '',
					participationMethod: ''
				};
				this.closeModal();
			}
		}
	};
</script>

<style>
	.event-detail-container {
		padding: 20px;
		background-color: #f9f9f9;
	}

	.event-cover {
		width: 100%;
		height: 250px;
		object-fit: cover;
		border-radius: 12px;
		margin-bottom: 30px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
	}

	/* 新增赛事信息卡片样式 */
	.event-info-card {
		background-color: #fff;
		padding: 30px;
		border-radius: 12px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
		margin-bottom: 30px;
	}

	.event-info {
		display: flex;
		flex-direction: column;
	}

	.info-item {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
		margin-top: 10px;
	}

	.info-label {
		width: 120px;
		font-size: 16px;
		font-weight: 500;
		color: #666;
	}

	.info-value {
		font-size: 16px;
		color: #333;
	}

	.event-introduction,
	.event-registration {
		background-color: #fff;
		padding: 30px;
		border-radius: 12px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
		margin-bottom: 30px;
	}

	.section-title {
		font-size: 24px;
		font-weight: bold;
		margin-bottom: 20px;
		color: #333;
	}

	.event-description {
		display: block;
		font-size: 16px;
		color: #666;
		line-height: 1.6;
		margin-top: 10px;
	}

	.register-button {
		margin-top: 20px;
		background-color: #007aff;
		color: #fff;
		padding: 15px 30px;
		border-radius: 12px;
		text-align: center;
		font-size: 18px;
		transition: background-color 0.3s ease;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
	}

	.register-button[disabled] {
		background-color: #ccc;
		cursor: not-allowed;
		box-shadow: none;
	}

	.register-button:hover:not([disabled]) {
		background-color: #0056b3;
	}

	/* 对话框样式 */
	.modal {
		display: none;
		position: fixed;
		z-index: 1;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		overflow: auto;
		background-color: rgba(0, 0, 0, 0.4);
	}

	.show-modal {
		display: block;
	}

	.modal-content {
		background-color: #fefefe;
		margin: 15% auto;
		padding: 20px;
		border: 1px solid #888;
		width: 400px;
	}

	.close {
		color: #aaa;
		float: right;
		font-size: 28px;
		font-weight: bold;
	}

	.close:hover,
	.close:focus {
		color: black;
		text-decoration: none;
		cursor: pointer;
	}

	form {
		display: flex;
		flex-direction: column;
	}

	.form-row {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
	}

	.form-row label {
		margin-right: 10px;
		width: 120px;
	}

	.form-row input,
	.form-row select {
		flex: 1;
		padding: 8px;
		border: 1px solid #ccc;
		border-radius: 4px;
	}

	.error-message {
		color: red;
		font-size: 12px;
		margin-top: -10px;
		margin-bottom: 10px;
		margin-left: 120px;
	}

	.button-group {
		display: flex;
		/* 启用 flex 布局 */
		justify-content: center;
		/* 主轴（水平方向）居中对齐 */
		align-items: flex-start;
		/* 交叉轴（垂直方向）顶部对齐，可按需调整 */
		gap: 10px;
		/* 设置按钮之间的间距为 10px，可以根据需求调整 */
		margin-top: 20px;
		/* 可以根据实际情况调整顶部外边距 */
	}

	.button-group button {
		width: auto;
		/* 让按钮宽度自适应内容 */
		padding: 10px 20px;
		/* 调整按钮内边距，可根据需要修改 */
	}

	button[type="submit"] {
		background-color: #007BFF;
		color: white;
		border: none;
		cursor: pointer;
		transition: background-color 0.3s ease;
		margin-left: 100px;
	}

	button[type="submit"]:hover {
		background-color: #0056b3;
	}

	button[type="button"] {
		background-color: #a6abaa;
		color: white;
		border: none;
		cursor: pointer;
		transition: background-color 0.3s ease;
		margin-right: 100px;
	}

	button[type="button"]:hover {
		background-color: #8b908f;
	}
</style>